package cn.janyd.jmall.web.core.interceptor;

import cn.janyd.jmall.web.core.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 访问日志记录
 *
 * @author janyd
 * @since 2020/8/5 21:54
 */
public class AccessLogInterceptor extends HandlerInterceptorAdapter {
    private final static Logger logger = LoggerFactory.getLogger(AccessLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录当前时间
        WebUtil.setAccessStartTime(request, System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Map<String, Object> accessLog = new HashMap<>(10);
        accessLog.put("uri", request.getRequestURI());
        accessLog.put("method", request.getMethod());
        accessLog.put("userAgent", request.getHeader("User-Agent"));
        //TODO 获取IP
//        accessLog.put("ip", );
        long startTime = WebUtil.getAccessStartTime(request);
        accessLog.put("startTime", WebUtil.getAccessStartTime(request));
        accessLog.put("responseTime", (System.currentTimeMillis() - startTime));

        if (logger.isDebugEnabled()) {
            logger.debug(accessLog.toString());
        }
    }
}
